from fastapi import APIRouter, Depends
from models.Models import Content
from db.DBUtil import DBUtil
from utils.result_back import success, fail
from datetime import datetime
from vos.Vos import ContentVo
from fastapi_jwt_auth import AuthJWT

router = APIRouter()


@router.post("/list/{page_index}/{page_size}")
def list_content(page_index: int, page_size: int, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    contents = session.query(Content).order_by(Content.id.desc()).limit(page_size).offset(
        (page_index - 1) * page_size).all()
    count = session.query(Content).count()
    db_util.close()
    result = {
        'records': contents,
        'total': count,
        'current': page_index
    }
    return success(result)


@router.get("/findById/{content_id}")
def find_content(content_id: int, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    content = session.query(Content).filter(Content.id == content_id).first()
    db_util.close()
    return success(content)


@router.put("/updateById")
def update_content(content_vo: ContentVo, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    old_content = session.query(Content).filter(Content.id == content_vo.id).first()
    if old_content:
        old_content.title = content_vo.title
        old_content.author = content_vo.author
        old_content.content = content_vo.content
        old_content.category_code = content_vo.category_code
        old_content.update_time = datetime.now()
        session.commit()

    db_util.close()
    return success(old_content)


@router.post("/add")
def add_content(content_vo: ContentVo, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    content = Content()
    content.title = content_vo.title
    content.author = content_vo.author
    content.content = content_vo.content
    content.category_code = content_vo.category_code
    content.update_time = datetime.now()
    content.create_time = datetime.now()

    session.add(content)
    session.commit()

    db_util.close()
    return success(content)
